from django.core.cache import cache
from home.models import Banner
from django.conf import settings
from home.serializer import Bannerserializer
from celery import shared_task


@shared_task
def update_banner():
    queryset = Banner.objects.all().filter(is_delete=False, is_show=True).order_by('orders')[0:settings.BANNER_COUNT]
    ser = Bannerserializer(instance=queryset, many=True)
    for item in ser.data:
        item['image'] = settings.BACKEND_URL + item['image']
    cache.set('banner_list', ser.data)
    return '轮播图缓存更新成功'


from celery import Task
from django.core.mail import send_mail
from django.conf import settings


class SendEmailTask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        info = f'任务成功-- 任务id是:{task_id} , 参数是:{args} , 执行成功 !'
        send_mail('celery任务监控成功告警', info, settings.EMAIL_HOST_USER, ["2782557724@qq.com", ])
        print('------------成功')

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        info = f'任务失败-- 任务id为:{task_id} , 参数为:{args} , 失败 ! 失败信息为: {exc}'
        send_mail('celery任务监控失败告警', info, settings.EMAIL_HOST_USER, ["2782557724@qq.com", ])
        print('------------失败')

    def on_retry(self, exc, task_id, args, kwargs, einfo):
        print(f'任务id位：:{task_id} , 参数为:{args} , 重试了 !  错误信息为: {exc}')


import time, random


@shared_task
def seckill(course_id):
    print('根据课程id：%s，查询课程是否还有剩余，耗时2s' % course_id)
    time.sleep(2)
    res = random.choice([True, False])
    if res:  # 库存够
        print('扣减库存，耗时1s')
        time.sleep(1)
        print('下单，耗时2s')
        time.sleep(2)
        return True
    else:
        return False
